#include "simple_socket.h"
#include <boost/filesystem.hpp>

void Mario_Socket::sock_create(string address)
{
  // setting socket properties
  bzero((char *) &serv_addr, sizeof(serv_addr));
  serv_addr.sun_family = AF_UNIX;
  strcpy(serv_addr.sun_path, address.c_str());
  servlen=strlen(serv_addr.sun_path) + sizeof(serv_addr.sun_family);

  // create new unix socket
  if ((sockfd = socket(AF_UNIX,SOCK_STREAM,0)) < 0)
    sock_error("creating socket");

  // bind socket
  if(bind(sockfd,(struct sockaddr *)&serv_addr,servlen)<0)
    sock_error("binding socket");


  // listen, accept => new socket
  listen(sockfd,5);
  clilen = sizeof(cli_addr);
  newsockfd = accept(
       sockfd,(struct sockaddr *)&cli_addr,&clilen);
  if (newsockfd < 0)
    sock_error("accepting");

}

void Mario_Socket::sock_close()
{
  // close sockets
  close(newsockfd);
  close(sockfd);

  // delete socket from filesystem
  boost::filesystem::remove(serv_addr.sun_path);
}

void Mario_Socket::sock_error(const char *msg)
{
    printf("ERROR: %s\n", msg);
}



/** Userinputinterface, Useroutputinterface **/
string Mario_Socket::read_from_user()
{
  string ret;

  n = read(newsockfd, buf, 4096);

  ret.insert(0, buf, n);
  return ret;
}

bool Mario_Socket::write_to_user(string s)
{
//    s = s + "\t";
    s = "<>" + s;  // XXX blöder hack..
    write(newsockfd,s.c_str(), strlen(s.c_str()));  // FIXME Absturz wenn Client Socket geschlossen!
    return true;
}

